<template>
  <div v-loading="loading" class="list-table">
    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item :label="$t('年份')" prop="yearS">
        <DatePicker v-model="queryParams.yearS" type="year" value-format="yyyy" :placeholder="$t('开始-年')" />
      </el-form-item>
      <el-form-item :label="$t('至')" prop="yearE" label-width="20">
        <DatePicker v-model="queryParams.yearE" type="year" value-format="yyyy" :placeholder="$t('结束-年')" />
      </el-form-item>
      <el-form-item :label="$t('报告周期')" prop="type">
        <el-select v-model="queryParams.type" value="" :placeholder="$t('报告周期')" clearable>
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="$t(dict.dictLabel)"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t("搜索") }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("重置") }}</el-button>
        <el-button v-hasPermi="['company:pcw:export']" type="warning" icon="el-icon-download" size="mini" @click="exportHandle">{{ $t("导出") }}</el-button>
      </el-form-item>
    </el-form>

    <el-tabs v-model="view_table" @tab-click="tab_click">
      <el-tab-pane :label="$t('资产负债表')" name="balance_sheet" />
      <el-tab-pane :label="$t('利润表')" name="income_sheet" />
      <el-tab-pane :label="$t('现金流量表')" name="cash_flow_sheet" />
    </el-tabs>
    <div :style="{ overflow: 'auto', 'height': (windowHeight + 20) + 'px' }">
      <el-table
        ref="scrollTable"
        class="el-table__body-wrapper is-scrolling-right custom-table"
        :data="pcwDataBaseList"
        border
        stripe
        :height="windowHeight"
      >
        <el-table-column
          v-for="(col) in columns"
          :key="`${col.key}`"
          :align="col.prop !== 'subjectName' ? 'right' : 'left'"
          :prop="col.prop"
          :label="col.label? $t(col.label): ($t(col.labelYear) + ' - ' + $t(col.labelType) + '('+$t(col.labelSource)+')')"
          :fixed="col.prop === 'subjectName'"
          :width="col.prop !== 'subjectName' ? '200' : '220'"
        >
          <template slot="header" slot-scope="scope">
            <span>
              <span>{{ scope.column.label }}</span>
              <el-tooltip class="item" effect="light" content="点击数值进行编辑" placement="top-start">
                <i v-if="col.prop == 'subjectName'" class="el-icon-question" />
              </el-tooltip>
              <i
                v-if="col.prop !== 'subjectName' && checkPermi(['company:pcw:edit'])"
                :class="col.prop===updateMainId?'el-icon-circle-close':'el-icon-edit'"
                style="cursor: pointer;padding-left: 5px;"
                @click="updataHandle(col.prop)"
              />
            </span>
            <!-- @click="deleteHandle(col.prop)" -->
          </template>
          <template slot-scope="scope">
            <span v-if="col.prop === 'subjectName'">
              {{ $t(scope.row.subjectName) }}
            <!-- {{ $t(scope.row[col.prop]) }} -->
            </span>
            <span v-else-if="col.prop !== 'subjectName' && col.prop !=='keyCode'">
              <span
                v-if="scope.row[col.prop] && !scope.row[col.prop]['isChange']"
                class="update_val"
                @click="clickUpdateValue(scope.row, col)"
              >
                {{ formattedNumber(scope.row[col.prop]['val']) }}
                <!-- <i class="el-icon-edit" style="cursor: pointer;padding-left: 5px;" @click="clickUpdateValue(scope.row, col)" /> -->
              </span>
              <money
                v-else-if="scope.row[col.prop] && scope.row[col.prop]['isChange']"
                :ref="col.key"
                :key="`${col.key}`"
                v-model="scope.row[col.prop]['val']"
                :clearable="false"
                @change="asyncSaveKey($event, scope.row, col)"
                @blur="blurHiddenInput(scope.row,col)"
              />
              <span v-else>
                <i class="el-icon-edit" style="cursor: pointer;padding-left: 5px;" @click="clickUpdateValue(scope.row, col)" />
              </span>
            </span>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="isLoadingPage" style="text-align: right;width: 100%;z-index: 2002;margin: -40px;">
        <i class="el-icon-loading" />
      </div>
    </div>
  </div>
</template>

<script>
import { listGroupPcwDataBase, asyncSaveKey } from '@/api/company/pcw/pcwDataBase'
import { delPcwDataMain } from '@/api/company/pcw/pcwDataMain'
import { checkPermi } from '@/utils/permission'
export default {
  props: {
    companyId: {
      type: String,
      required: false,
      default: ''
    }
  },
  data() {
      return {
          // 遮罩层
          loading: true,
          // 财务数据基础数据集合
          pcwDataBaseList: [],
          columns: [],
          dataSourceOptions: [],
          // 查询参数
          queryParams: {
              companyId: this.$route.query.companyId || this.$route.query.id,
              belongsTable: '',
              pageNum: 1,
              pageSize: 10,
              type: undefined
          },
          // 表单参数
          form: {},
          // 报告类型
          typeOptions: [],
          // 表单校验
          rules: {},
          // 表格tab
          view_table: 'balance_sheet',
          // 表头展示
          baseTit: [],
          // 主数据ID
          dataMainIds: [],
          // 修改基础数据提交后台
          dataBaseForm: {},
          windowHeight: document.documentElement.clientHeight - 280, // 实时屏幕高度
          isLoadingPage: false,
          pageNum: 1,
          pageSize: 10,
          total: 0,
          updataStatus: false,
          updateMainId: '' // 修改的时候的id
      }
  },
  watch: {
    companyId: {
      handler(val) {
        if (val) {
          this.queryParams.companyId = val
          this.getList()
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
      // 财务数据报告周期
      this.getDicts('financial_type').then(response => {
        this.typeOptions = response.data
      })
      this.getDicts('pcw_data_source').then(response => {
        this.dataSourceOptions = response.data
      })
      this.dataMainIds.push('')
  },
  mounted() {
    this.getList()
    var that = this
    // <!--把window.onresize事件挂在到mounted函数上-->
    window.onresize = () => {
      return (() => {
        that.windowHeight = document.documentElement.clientHeight - 280 // 高
      })()
    }
    this.initLoadAddPage()
  },
  methods: {
    checkPermi,
    columnConsole(column) {
      console.log(column)
    },
    /** 查询上传财务数据主表列表 */
    getList() {
        // 初始化数据
        this.pcwDataBaseList = []
        this.columns = []
        this.pageNum = 1
        this.pageSize = 10
        this.total = 0
        this.loading = true
        this.queryParams.belongsTable = this.view_table
        this.getListStart()
    },
    dataSourceFormat(row) {
      return this.selectDictLabel(this.dataSourceOptions, row.dataSource)
    },
    // 表单重置
    reset() {
        this.form = {
            id: undefined,
            companyId: this.$route.query.companyId || this.$route.query.id,
            year: undefined,
            type: undefined,
            attachmentId: undefined,
            createBy: undefined,
            createTime: undefined,
            updateBy: undefined,
            updateTime: undefined,
            delFlag: undefined,
            remark: undefined,
            yearS: undefined,
            yearE: undefined
        }
        this.resetForm('form')
    },
    /** 搜索按钮操作 */
    queryHandle() {
        this.baseTit = []
        this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
        this.resetForm('queryForm')
        this.queryHandle()
    },
    /** 删除按钮操作 */
    deleteHandle(id) {
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return delPcwDataMain(id)
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('删除成功'))
      }).catch(function() {
      })
    },
    // 切换页签操作
    tab_click(tab) {
      this.view_table = tab.name
      this.getList()
    },
    // 修改value操作
    clickUpdateValue(row, col) {
      if (checkPermi(['company:pcw:edit'])) {
        if (row[col.prop]) {
          if (isNaN(row[col.prop].val)) {
            this.$set(row[col.prop], 'val', 0)
          }
          this.$set(row[col.prop], 'isChange', true)
        } else {
          // 代表着新增
          const o = {
            isChange: true,
            keyId: undefined,
            val: undefined
          }
          //  row[col.prop] = Object.assign({}, row[col.prop], o)
          this.$set(row, col.prop, o)
        }
      }
     // 光标获取焦点
      this.$nextTick(() => {
          // 这里为什么是两个呢？
          this.$refs[col.key].map(el => {
            const inputElement = el.$refs.money.$refs.input
            inputElement.focus()
          })
        })
    },
    // blur 光标离开文本框
    switchShow(row, col) {
      // 保存数据
      var keyValue = row[col.prop]['val']
      if (keyValue === '' || keyValue === undefined) {
        // this.msgError(this.$t('必填信息'))
        return false
      }
      this.asyncSaveKey(row, col)
    },
    blurHiddenInput(row, col) {
      row[col.prop]['isChange'] = false
    },
    // 按回车，光标离开文本框，变为数字，后台异步计算科目值
    asyncSaveKey(val, row, col) {
      row[col.prop]['isChange'] = false
      var keyValue = val
      if (keyValue === '' || keyValue === undefined) {
        // this.msgError(this.$t('必填信息'))
        return false
      }
      var keyId = row[col.prop]['keyId']
      this.dataBaseForm.keyValue = keyValue
      this.dataBaseForm.id = keyId
      this.dataBaseForm.mainId = col.prop
      this.dataBaseForm.keyName = row.subjectName
      this.dataBaseForm.companyId = this.$route.query.companyId || this.$route.query.id
      asyncSaveKey(this.dataBaseForm).then(res => {
        row[col.prop]['isChange'] = false
        return this.msgSuccess(res.msg)
      })
    },
    exportHandle() {
      this.downLoadExcel('/pcw/pcwDataBase/export/', this.queryParams)
    },
    initLoadAddPage() {
      // 滑动翻页
      this.$refs.scrollTable.bodyWrapper.addEventListener('scroll', (res) => {
        const height = res.target
        const clientWidth = height.clientWidth
        const scrollWidth = height.scrollWidth
        const scrollLeft = height.scrollLeft
        if (scrollLeft > (scrollWidth - clientWidth - 100) && scrollLeft !== 0) {
          // 如果当前长度大于total 就不能进行分页查询了
          const limit = this.pageNum * this.pageSize
          if (!this.isLoadingPage && (this.total === 0 || this.total > limit)) {
            this.isLoadingPage = true
            this.pageNum++
            // console.log('this.pageNum', this.pageNum)
            this.getListStart()
          }
        }
      }, true)
    },
    getListStart() {
         if (!this.isLoadingPage && (this.total !== 0)) {
            this.isLoadingPage = false
        } else {
            this.loading = true
            this.queryParams.pageNum = this.pageNum
            this.queryParams.pageSize = this.pageSize
          listGroupPcwDataBase(this.queryParams).then(response => {
            if (this.pageNum === 1) {
              this.pcwDataBaseList = response.data.data
              this.columns = response.data.columns
              this.total = response.data.total
            } else {
              if (response.data.columns) {
              response.data.columns.forEach(item => {
                 if (item.prop !== 'subjectName') {
                   this.columns.push(item)
                  }
               })
              }
              response.data.data.forEach(item => {
                if (item['subjectName'] !== undefined) {
                  this.pcwDataBaseList.forEach(sub => {
                    if (item['subjectName'] === sub['subjectName']) {
                      for (var i in item) {
                        if (i !== 'subjectName' && i !== 'keyCode') {
                          this.$set(sub, i, item[i])
                          // sub[i] = item[i]
                        }
                      }
                    }
                  })
                }
              })
            }
            this.$forceUpdate()
            this.initDataEnd()
        })
      }
    },
     initDataEnd() {
      this.loading = false
      this.isLoadingPage = false
      this.initLoadAddPage()
    },
    updataHandle(mainId) {
        this.updateMainId = mainId
        this.updataStatus = !this.updataStatus
        if (!this.updataStatus) {
          this.updateMainId = ''
        }
        this.pcwDataBaseList.map(item => {
          if (isNaN(item[mainId].val)) {
          this.$set(item[mainId], 'val', 0)
        }
          this.$set(item[mainId], 'isChange', this.updataStatus)
        })
    },
    formatMoney(value) {
      if (!isNaN(value)) {
          return parseFloat(value).toFixed(2)
      } else {
          return value
      }
    },
     formattedNumber(val) {
      val = this.formatMoney(val)
      if (val != null && !isNaN(Number(val))) {
      if (typeof val === 'string') {
        return parseFloat(val).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      } else if (typeof val === 'number') {
        // 对于负数，先取绝对值进行格式化，然后再加上负号
        const formattedValue = Math.abs(val).toLocaleString('en-US', {
          style: 'decimal',
          minimumFractionDigits: 2,
          maximumFractionDigits: 2
        })
      return val < 0 ? '-' + formattedValue : formattedValue
    }
  } else {
    return val
  }
    }
  }
}
</script>
<style scoped>
.el-table__body-wrapper {
       transition: none !important;
}
/* .custom-table /deep/.el-table__row {
  height: 50px;
  line-height: 50px;
} */
.update_val{
  cursor: pointer;
}
</style>
